/*
 * Copyright 2020. hi-dhl (Jack Deng)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.working.libbase.initializer

import android.app.Application
import android.content.Context
import androidx.startup.Initializer
import com.alibaba.android.arouter.launcher.ARouter
import com.tencent.mmkv.MMKV
import com.working.libbase.BuildConfig
import com.working.libcommon.helper.AndroidHelper
import com.working.libbase.storage.Storage
import com.working.libcommon.util.LogUtils
import com.working.libcommon.util.NetworkStatusMonitor
import com.working.libnet.di.httpModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.logger.Level

class AppInitializer : Initializer<Unit> {
    override fun create(context: Context) {
        LogUtils.e("AppInitializer create")
        AndroidHelper.application = context.applicationContext as Application
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        MMKV.initialize(context)
        Storage.numberOfStartUp = Storage.numberOfStartUp?.plus(1)
        ARouter.init(AndroidHelper.application) // 尽可能早，推荐在Application中初始化
        NetworkStatusMonitor.inject(context)
        Thread.setDefaultUncaughtExceptionHandler { t, e -> LogUtils.e(e) }
        startKoin {
            androidLogger(Level.ERROR)
            androidContext(context)
            modules(httpModule)
        }
    }

    override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf()
}